# -*- coding: utf-8 -*-
# @Time     : 2020/6/28 10:46
# @Author   : 马鹏
# @Software : PyCharm
import requests
import chardet
import re
from lxml import etree
from urllib import parse
from threading import Thread
import os
import json
# from .my_base import MyBase

class YingHua:
    url = 'http://m.imomoe.in/search.asp'
    # 蘑菇隧道代理服务器地址
    headers = {
        'User-Agent': 'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/83.0.4103.97Safari/537.36',
    }
    def __init__(self,keyword):
        self.keyword = keyword
        # test = parse.quote(keyword, 'gbk')
        self.params = {
            'searchword':keyword,
        }

    def request_url(self,url,ma=0): #请求方法
        shu = ma
        shu += 1
        try:
            resp = requests.get(url=url, headers=self.headers, verify=False)
            if resp.status_code == 200 and resp:
                self.a = 0
                # print('hhhhh')
                return resp
            else:
                raise Exception
        except Exception :
            if shu >5:
                raise Exception('请求失败！')
            else:
                resp = self.request_url(url,shu)
                return resp

    def my_request(self,url):
        resp = requests.get(url=url, headers=self.headers)
        bm = chardet.detect(resp.content)
        resp.encoding = bm.get('encoding')
        return resp

    def request_page_one(self):
        res = requests.post(url=self.url,headers=self.headers,params=self.params,verify=False)
        bm =  chardet.detect(res.content)
        res.encoding=bm.get('encoding')
        # print(res.text)
        return res.text

    def read_file(self,dir):
        list_exist = []
        files = os.listdir(dir)
        for i in files:
            jishu = i.split('-')[-1].split('.')[0]
            list_exist.append(jishu)
        return list_exist

    def my_xpath(self,data,ruler):
        return etree.HTML(data).xpath(ruler)

    def parse_page_one(self,resp):
        url_list = self.my_xpath(resp,'//*[@id="mobile-index"]/ul[1]/li/div/a/@href')
        print(url_list)

    def get_page_two(self,url):
        resp = self.my_request(url)
        title = self.my_xpath(resp.text,'//*[@id="play_0"]/ul/li/a/@title')
        url_list = ['http://m.imomoe.in'+i for i in self.my_xpath(resp.text,'//*[@id="play_0"]/ul/li/a/@href')]
        return zip(title,url_list)

    def get_video_one(self,keyword,url_one): #获取视频方法一  需要selenium，异步加载
        for title,url in self.get_page_two(url_one):
            video_url = self.my_xpath(self.my_request(url).text,'//*[@id="a1"]/div[2]/video/@src')[0]
            content = self.my_request(video_url).content
            path_dir = 'F:\动漫\{}'.format(keyword)
            name = keyword+'-'+title
            self.save_file(path_dir,name,content)


    def get_video_two(self,keyword,url_one):#获取视频方法二
        res = self.my_request(url_one).text
        js_url = 'http://m.imomoe.in'+self.my_xpath(res,'//div[@class="player"]/script/@src')[0]
        resp = self.my_request(js_url).text
        video_url_list = re.findall(r"var *VideoListJson=\[\['.*?',(.*?)\],\['.*?'.*?,",resp)[0]
        video_url_list = video_url_list.replace("'",'"')
        path_dir = 'E://动漫/{}'.format(keyword)
        list_exist = self.read_file(path_dir)
        # print(video_url_list)
        video_url_list = json.loads(str(video_url_list))
        for video_url_con in video_url_list:
            video_url_li = video_url_con.split('$')
            title = video_url_li[0]
            video_url = video_url_li[1]
            if title in list_exist:
                continue
            # self.download_video(title,video_url,keyword)
            Thread(target=self.download_video,args=(title,video_url,keyword)).start()
            print(title,video_url)

    def mk_file(self,file):
        try:
            os.mkdir(file)
        except FileExistsError:
            pass

    def download_video(self,title,video_url,keyword):
        path_dir = 'E://动漫/{}'.format(keyword)
        # self.mk_file(path_dir)
        name = keyword + '-' + title
        print('{}正在下载中...'.format(name))
        content = self.request_url(video_url).content
        # content = b'aaa'
        self.save_file(path_dir, name, content)

    def save_file(self,path_dir,name,content):
        try:
            os.makedirs(path_dir)
        except FileExistsError:
            pass
        filename =path_dir+'/'+name+'.mp4'
        print(filename+'---->正在保存！')
        with open(filename,'wb') as f:
            f.write(content)
        print('{}下载结束！'.format(name))
        # print(filename)
    def run(self):
        # resp = self.request_page_one()
        # self.parse_page_one(resp)
        # print(resp)
        #self.get_video_one(self.keyword,'http://m.imomoe.in/view/7652.html')
        self.get_video_two(self.keyword,'http://www.imomoe.in/player/7840-0-0.html')
if __name__ == '__main__':
    yh = YingHua('魔王学院的不适合者')
    yh.run()
    # print(yh.read_file('E:\动漫\租借女友'))